﻿using System.Data;
using System.Security.Cryptography.X509Certificates;
using MySqlConnector;
using System;
using System.Windows.Forms;

namespace Front._1124;

public partial class AddBookForm : Form
{
    public AddBookForm()
    {
      public partial class AddBookForm : Form
    {
        public AddBookForm()
        {
            InitializeComponent();
            dtpPublishDate.Value = DateTime.Now;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(txtBookName.Text) ||
                string.IsNullOrWhiteSpace(txtAuthor.Text) ||
                string.IsNullOrWhiteSpace(txtCategory.Text) ||
                string.IsNullOrWhiteSpace(txtPublisher.Text) ||
                string.IsNullOrWhiteSpace(txtStock.Text))
            {
                MessageBox.Show("请填写所有必填字段！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (!int.TryParse(txtStock.Text, out int stock) || stock < 0)
            {
                MessageBox.Show("库存必须为非负整数！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            try
            {
                string connStr = "server=localhost;port=3306;database=book;user=root;password=root;charset=utf8mb4;AllowPublicKeyRetrieval=True;";
                using (MySqlConnection conn = new MySqlConnection(connStr))
                {
                    conn.Open();
                    int writerId = 0;
                    string checkWriterSql = "SELECT id FROM writer_info WHERE writer_name = @writerName;";
                    using (MySqlCommand checkCmd = new MySqlCommand(checkWriterSql, conn))
                    {
                        checkCmd.Parameters.AddWithValue("@writerName", txtAuthor.Text.Trim());
                        object result = checkCmd.ExecuteScalar();
                        if (result == null)
                        {
                            string insertWriterSql = "INSERT INTO writer_info (writer_name) VALUES (@writerName); SELECT LAST_INSERT_ID();";
                            using (MySqlCommand insertWriterCmd = new MySqlCommand(insertWriterSql, conn))
                            {
                                insertWriterCmd.Parameters.AddWithValue("@writerName", txtAuthor.Text.Trim());
                                writerId = Convert.ToInt32(insertWriterCmd.ExecuteScalar());
                            }
                        }
                        else
                        {
                            writerId = Convert.ToInt32(result);
                        }
                    }

                    string insertBookSql = @"INSERT INTO book_info (book_name, writer_id, category, publisher, publish_date, stock) 
                                           VALUES (@bookName, @writerId, @category, @publisher, @publishDate, @stock);";
                    using (MySqlCommand insertBookCmd = new MySqlCommand(insertBookSql, conn))
                    {
                        insertBookCmd.Parameters.AddWithValue("@bookName", txtBookName.Text.Trim());
                        insertBookCmd.Parameters.AddWithValue("@writerId", writerId);
                        insertBookCmd.Parameters.AddWithValue("@category", txtCategory.Text.Trim());
                        insertBookCmd.Parameters.AddWithValue("@publisher", txtPublisher.Text.Trim());
                        insertBookCmd.Parameters.AddWithValue("@publishDate", dtpPublishDate.Value);
                        insertBookCmd.Parameters.AddWithValue("@stock", stock);
                        insertBookCmd.ExecuteNonQuery();
                    }

                    MessageBox.Show("图书添加成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.Close();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"添加失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}